//
//  DMTools.m
//  DaMaoMall
//
//  Created by HXHL-wally on 16/7/21.
//  Copyright © 2016年 daMao-wally. All rights reserved.
//

#import "DMTools.h"

@implementation DMTools

DEFINE_SINGLETON_FOR_CLASS(DMTools)

//获取Appdelegate 指针
+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

//jsonkit 解析json格式
//+ (NSDictionary *)JSonFromString:(NSString* )result
//{
//    NSDictionary *json = [result objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
//    return json;
//    
//}

//显示指示器
+ (void)showProgress:(UIView *) view
{
//    [SVProgressHUD showHUDAddedTo:view animated:YES];
    
}

//显示指示器和文字
+ (void)showProgress:(UIView *) view showText:(NSString*)text
{
//    SVProgressHUD * hud = [SVProgressHUD showHUDAddedTo:view animated:YES];
//    hud.labelText = text;
}

//显示指示器文字
+ (void) showTips:(NSString *)text toView:(UIView *)view
{
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.mode = MBProgressHUDModeText;
//    hud.labelText = text;
//    [hud show:YES];
//    [hud hide:YES afterDelay:0.7];
}

//显示成功标识指示器和文字以及自定义图片
+ (void)showSuccessTips:(NSString *)text image:(UIImage *)image toView:(UIView *)view
{
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
//    hud.backgroundColor = [UIColor clearColor];
//    hud.mode = MBProgressHUDModeCustomView;
//    hud.color = [UIColor clearColor];
//    hud.customView = [[UIImageView alloc] initWithImage:image];
//    [hud show:YES];
//    [hud hide:YES afterDelay:1];
}

//显示失败标识指示器和文字
+ (void)showErrorTips:(NSString *)text toView:(UIView *)view
{
    
}

//隐藏指示器
+ (void)hideProgress:(UIView *)view
{
//    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}

//将字典、数组转换成json串
+(NSString *)stringFromObject:(id)obj{
    return [obj JSONString];
}

//将json串反解析
//+(id)objectFromString:(NSString *)str{
//    
////    return [str objectFromJSONString];
//}

//获取uuid
-(NSString *)gen_uuid
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    
    CFRelease(uuid_ref);
    NSString * uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    
    CFRelease(uuid_string_ref);
    return uuid;
}

//判断当前时间和过去时间的时间差
- (NSString *)intervalSinceNow:(NSString *) theDate
{
    if (!STRING_NOT_EMPTY(theDate)){
        return nil;
    }
    if (theDate.length !=19){
        return @"时间格式错误";
    }
    NSString *yearStr = [theDate substringToIndex:4];
    
    
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *timeString=@"";
    
    NSString *nowTime = [NSString stringWithFormat:@"%@",
                         [date stringFromDate:[NSDate date]]];
    NSString *nowYear = [nowTime substringToIndex:4];
    
    if (![nowYear isEqualToString:yearStr]) {   //不是今年，显示完整时间
        return [theDate substringToIndex:11];
    }
    
    NSString * str1 = [theDate substringWithRange:NSMakeRange(8, 2)];
    NSString * str2 = [nowTime substringWithRange:NSMakeRange(8, 2)];
    if ([str2 compare:str1]==0){        //今天显示时分秒
        timeString = [theDate substringWithRange:NSMakeRange(11, 5)];
    }else{                              //过去显示月日
        timeString = [theDate substringWithRange:NSMakeRange(5, 11)];
    }
    
    return timeString;
}

+(void)moveFileToDocument:(NSString *)name andType:(NSString *)type
{
    //1.获取文件在工程中的路径--源路径
    NSString * sourcesPath = [[NSBundle mainBundle] pathForResource:name ofType:type];
    
    //2.获取沙盒中Document文件夹的路径--目的路径
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentPath = [paths objectAtIndex:0];
    NSString * desPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",name,type]];
    DMLog(@"desPath = %@",desPath);
    //3.通过NSFileManager类，将工程中的数据库文件复制到沙盒中。
    NSFileManager * fileManager  =[NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:desPath]){
        NSError * error;
        if ([fileManager copyItemAtPath:sourcesPath toPath:desPath error:&error]){
            DMLog(@"文件移动成功");
        }else{
            DMLog(@"文件移动失败");
        }
    }else{
        DMLog(@"文件已存在");
    }
}

//Label自适应大小
+(CGRect )autoSizeOfWidget:(UILabel *)widget andSize:(CGSize)size andtextFont:(CGFloat )sizefont
{
    widget.numberOfLines = 0;
    CGRect rect = widget.frame;
    if ([widget.text length]==0){
        return CGRectMake(rect.origin.x, rect.origin.y, 0, 0);
    }
    //    if (IOS7_OR_IOS8){
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
    CGSize  actualsize =[widget.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, actualsize.width, actualsize.height);
    return tmpRect;
    //    }else{
    //        CGSize strSize = [widget.text sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
    //        CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, strSize.width, strSize.height);
    //        return tmpRect;
    //    }
}

//计算文字宽和长
+(CGRect)autoSizeOftext:(NSString *)text andSize:(CGSize)size andtextFont:(CGFloat)sizefont
{
    if (text == nil) {
        text = @"";
    }
    //    if (IOS7_OR_IOS8){
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
    CGSize  actualsize =[text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    CGRect tmpRect = CGRectMake(0, 0, actualsize.width, actualsize.height);
    return tmpRect;
    //    }else{
    //        CGSize strSize = [text sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
    //        CGRect tmpRect = CGRectMake(0, 0, strSize.width, strSize.height);
    //        return tmpRect;
    //    }
}


//图片无损拉伸
+(UIImage *)stretchableImag:(UIImage *)image
{
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(2,2,2,2)];
    return image;
}

/*

//获取数据库指针
+(FMDatabase*)getDb{
    //paths： ios下Document路径，Document为ios中可读写的文件夹
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"area.db"];
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    FMDatabase * db = [FMDatabase databaseWithPath:dbPath] ;
    return db;
}

//GET 请求 获取数据
+ (ASIHTTPRequest*)getRequestWithDict:(NSDictionary *)dict API:(NSString *)api
{
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    NSMutableString *params = [[NSMutableString alloc] init];
    for (id keys in muDict) {
        [params appendFormat:@"&%@=%@",keys,[muDict objectForKey:keys]];
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",HOST_URL,api,params];
    MCLOG(@"%@",urlStr);
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:url];
    [request setTimeOutSeconds:15];
    
    [request setRequestCookies:nil];
    [request setUseCookiePersistence:NO];
    
    return request;
}

//POST 请求 获取数据
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    
    
    MCLOG(@"post muDict :%@", muDict);
    MCLOG(@"post muDict :%@", url);
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    return request;
}

#warning 这个地方是测试地址  ---------只要删除text即可-----------------
//POST 请求 获取数据(测试地址)
+ (ASIFormDataRequest*)textpostRequestWithDict:(NSDictionary *)dict API:(NSString *)api
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    
    
    
    MCLOG(@"post muDict :%@", muDict);
    MCLOG(@"post muDict :%@", url);
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    return request;
}

#pragma mark 上面的地方是测试地址  ---------只要删除text即可-----------------


//POST 请求 上传文件
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api  fileName:(NSString *)filename  fileData:(NSData *)data
{
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    [request addData:data withFileName:filename andContentType:@"image/jpeg" forKey:@"img"];
    
    MCLOG(@"post muDict :%@", muDict);
    
    [request setUseCookiePersistence:NO];
    [request setUserAgentString:@"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"];
    return request;
}


//判断有无网络
+(BOOL)NetworkReachable
{
    NetworkStatus wifi = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
    NetworkStatus gprs = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if(wifi == NotReachable && gprs == NotReachable)
    {
        return NO;
    }
    return YES;
}

 */

//计算缓存
-(void)CalculateTheCache:(UILabel *)label
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        int size = [self sizeOfFolder:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
        NSString * lastSize = @"";
        if (size < (1024*1024)) {
            lastSize = [NSString stringWithFormat:@"%.1fKB",size/1024.0f];
        }else if(size > (1024*1024)){
            lastSize = [NSString stringWithFormat:@"%.1fMB",size/1024.0f/1024.0f];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            label.text = lastSize;
        });
    });
}

- (int)sizeOfFolder:(NSString*)folderPath
{
    NSArray *contents;
    NSEnumerator *enumerator;
    NSString *path;
    contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
    enumerator = [contents objectEnumerator];
    int fileSizeInt = 0;
    while (path = [enumerator nextObject]) {
        NSError *error;
        NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:path] error:&error];
        fileSizeInt +=[fattrib fileSize];
    }
    return fileSizeInt;
}

//清理缓存
-(void)clearTheCache:(UILabel *)label
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
        //        NSLog(@"files :%d",[files count]);
        
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            label.text=@"0.0KB";
            
        });
    });
}

//创建cell的分割线
-(UIView *)createSeparatorLineWithRect:(CGRect)rect
{
    UIView * view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = RGBA(200, 200, 200, 1);
    return view;
}

//打电话
+(void)MakeAPhoneCall
{
    NSString * num = [[NSString alloc] initWithFormat:@"tel://%@",@"4008186060"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:num]];
}

//编辑字符串颜色，大小
+(NSMutableAttributedString *)getAcolorfulStringWithTextArray:(NSArray *)array Color:(UIColor *)color Font:(UIFont *)font AllText:(NSString *)allText
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:allText];
    [str beginEditing];
    
    for (NSString * string in array) {
        if (str.length) {
            NSRange range1 = [allText rangeOfString:string];
            [str addAttribute:(NSString *)(NSForegroundColorAttributeName) value:color range:range1];
            if (font) {
                [str addAttribute:NSFontAttributeName value:font range:range1];
            }
        }
    }
    
    
    [str endEditing];
    
    return str;
}
//显示某个字符 颜色
+(NSMutableAttributedString *)getAcolorfulStringWithText1:(NSString *)text1 Color1:(UIColor *)color1 Font1:(UIFont *)font1 Text2:(NSString *)text2 Color2:(UIColor *)color2 Font2:(UIFont *)font2 AllText:(NSString *)allText
{
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:allText];
    [str beginEditing];
    if (text1) {
        NSRange range1 = [allText rangeOfString:text1];
        [str addAttribute:(NSString *)(NSForegroundColorAttributeName) value:color1 range:range1];
        if (font1) {
            //            CTFontRef helveticaBold = CTFontCreateWithName((CFStringRef)font1.fontName,font1.pointSize,NULL);
            //        [str addAttribute:(id)kCTFontAttributeName value:(id)helveticaBold range:range1];
            [str addAttribute:NSFontAttributeName value:font1 range:range1];
            
        }
    }
    
    if (text2) {
        NSRange range2 = [allText rangeOfString:text2];
        [str addAttribute:(NSString *)(NSForegroundColorAttributeName) value:color2 range:range2];
        if (font2) {
            [str addAttribute:NSFontAttributeName value:font2 range:range2];
            
        }
    }
    
    [str endEditing];
    
    return str;
}

+(BOOL)chickIphoneNumberRight:(NSString *)str
{
    NSString *regex = @"^((13[0-9])|(147)|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    return isMatch;
}

/*
 
////上传头像
+ (ASIFormDataRequest*)postRequestWithDict:(NSDictionary *)dict API:(NSString *)api data:(NSData *)data
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HOST_URL,api]];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    NSMutableDictionary *muDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    muDict[@"utype"] = @"2"; // 说明是ios的设备
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:15];
    for (id key in muDict) {
        [request setPostValue:[muDict objectForKey:key] forKey:key];
    }
    [request addData:data withFileName:@"KKK" andContentType:@"image/jpeg" forKey:@"img"];
    
    MCLOG(@"post muDict :%@", muDict);
    
    
    return request;
}

+ (NSMutableArray *)getArrayWithKey:(NSString *)key table:(NSString *)table
{
    NSMutableArray * array = [[NSMutableArray alloc] init];
    FMDatabase * db = [GZTools getDb];
    if (![db open]){
        MCLOG(@"open fail!");
        return nil;
    }
    NSString * queryString = @"";
    NSString * returenStr = @"";
    NSString * parentID = @"";
    
    
    
    if (key) {
        
        if ([table isEqualToString:@"city"]) {
            
            FMResultSet * rs = [db executeQuery:@"SELECT * FROM provience WHERE name = ?",key];
            
            while ([rs next]) {
                parentID = [rs objectForColumnName:@"id"];
            }
        }else if ([table isEqualToString:@"area"]) {
            
            FMResultSet * rs = [db executeQuery:@"SELECT * FROM city WHERE name = ?",key];
            
            while ([rs next]) {
                parentID = [rs objectForColumnName:@"id"];
            }
        }
        
        queryString = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE parentid = %@",table,parentID];
        
        FMResultSet * rs = [db executeQuery:queryString];
        
        while ([rs next]) {
            returenStr = [rs objectForColumnName:@"name"];
            [array addObject:returenStr];
        }
    }else {
        
        queryString = [NSString stringWithFormat:@"SELECT * FROM %@",table];
        
        FMResultSet * rs = [db executeQuery:queryString];
        
        while ([rs next]) {
            returenStr = [rs objectForColumnName:@"name"];
            [array addObject:returenStr];
        }
        
    }
    
    [db close];
    
    return array;
    
}



//-(BOOL)haveYouHuiQuan
//{
//    return [self getDataWithDict:@{@"CustomerID":[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID] } api:API_GETYOUHUIQUAN];
//
//}

-(BOOL)getDataWithDict:(NSDictionary *)dict api:(NSString *)api
{
    __block BOOL result = NO;
    if (![GZTools NetworkReachable]) {
        return result;
    }
    
    __weak ASIHTTPRequest *request = [GZTools postRequestWithDict:dict API:api];
    [request setCompletionBlock:^{
        
        NSDictionary *tempDic = [GZTools  JSonFromString:[request responseString]];
        
        MCLOG(@"temdic = %@",tempDic);
        
        if([[tempDic objectForKey:@"status"]intValue] == 1){
            NSArray * dataArray = tempDic[@"data"];
            for (NSDictionary * dic in dataArray) {
                if ([[dic objectForKey:@"status"]integerValue] == 2) {
                    result = YES;
                }
            }
        }
    }];
    
    [request setFailedBlock:^{
        
    }];
    [request startAsynchronous];
    
    return result;
}



#pragma mark -    修改
// gif 格式动画显示。
+ (void)showGifImageProgress:(UIView *)view
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES isWhite:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor clearColor];
    
    hud.customView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 212/2, 250/2)];
    //    hud.customView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 212, 250)];
    hud.customView.backgroundColor = [UIColor clearColor];
    
    [hud.customView sd_setImageWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"refreshImage1" ofType:@"gif"]] placeholderImage:nil];
    [hud show:YES];
}

 

#pragma mark -    修改
// 加载当前页面 gif格式动画显示。
+ (void)showLoadingGifImageProgress:(UIView *)view
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES isWhite:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.color = [UIColor clearColor];
    //    hud.color = [UIColor clearColor];
    hud.customView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200/2.0, 200/2.0)];
    
    //    UILabel *label = [[UILabel alloc] init];
    //    label.text = @"小微加载中...";
    //    label.frame = CGRectMake(0, hud.customView.height-5, hud.customView.width, 30);
    //    [hud.customView addSubview:label];
    //    label.textAlignment = NSTextAlignmentCenter;
    //    label.textColor = [UIColor whiteColor];
    //    label.font = [UIFont systemFontOfSize:12];
    
    
    //    hud.customView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 212, 250)];
    hud.customView.backgroundColor = [UIColor clearColor];
    
//    [hud.customView sd_setImageWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"refreshImage2" ofType:@"gif"]] placeholderImage:nil];
    [hud show:YES];
}
 
// AFH 框架封装
+ (void)postWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(successBlockAFH)success failure:(failureBlockAFH)failure
{
    
    NSString *urlNew = [NSString stringWithFormat:@"%@%@",HOST_URL,url];
    
    // 1.创建网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    // 2.发送网络请求请求数据
    [manager POST:urlNew parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (success) {
             success(responseObject);
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if (failure) {
             failure(error);
         }
     }];
}
// AFH 框架封装
+ (void)getWithUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(successBlockAFH)success failure:(failureBlockAFH)failure
{
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionaryWithDictionary:parameters];
    dictM[@"utype"] = @"2"; // 说明是ios的设备
    NSString *urlNew = [NSString stringWithFormat:@"%@%@",HOST_URL,url];
    // 1.创建网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 2.发送网络请求请求数据
    [manager GET:urlNew parameters:dictM success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (success) {
             success(responseObject);
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if (failure) {
             failure(error);
         }
     }];
}
 



+ (void)postWithHeaderWithUrl:(NSString *)url  parameters:(NSDictionary *)parameters  success:(successBlockAFH)success  failure:(failureBlockAFH)failure{
    
    NSString *urlNew = [NSString stringWithFormat:@"%@%@",HOST_URL,url];
    
    // 1.创建网络请求管理者
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    //封装header参数
    Account * accout = [IWAccountTool account];
    
    [manager.requestSerializer setValue:accout.token forHTTPHeaderField:@"Authorization"];
    
    // 2.发送网络请求请求数据
    [manager POST:urlNew parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (success) {
             success(responseObject);
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if (failure) {
             failure(error);
         }
     }];
    
}

*/


+ (CGSize )autolayoutSize :(UILabel *)lable{
    
    NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:lable.font,NSFontAttributeName, nil];
    CGSize size = [lable.text sizeWithAttributes:dic];
    return size;
}


#pragma mark - 设置 获取验证码 按钮60s不能点击

//设置 获取验证码 按钮60s不能点击
+(void)startTime:(UIButton *)button{
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timeNew = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timeNew,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(timeNew, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(timeNew);
            dispatch_async(dispatch_get_main_queue(), ^{
                [button setTitle:@"获取验证码" forState:UIControlStateNormal];
                button.userInteractionEnabled = YES;
                [button setBackgroundImage:[UIImage imageNamed:@"btn-hq"] forState:UIControlStateNormal];
                [button setBackgroundColor:[UIColor clearColor]];
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                // NSLog(@"____%@",strTime);
                [button setTitle:[NSString stringWithFormat:@"重发 (%@)",strTime] forState:UIControlStateNormal];
                button.userInteractionEnabled = NO;
                [button setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [button setBackgroundColor:[UIColor lightGrayColor]];
            });
            timeout--;
        }
    });
    dispatch_resume(timeNew);
    
}

#pragma mark - 将个人信息全部存储到个人偏好里
+ (void)saveValueToUserDefaults:(id)value andKey:(NSString *)key
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setValue:value forKey:key];
    [defaults synchronize];
}

#pragma mark - 把字典转化成为 json 串

+(NSString*)dictionaryToJson:(NSDictionary *)dict{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}



@end
